﻿Imports System.Xml

Public Class frmSubjects

    Dim classObject As XmlFunction = New XmlFunction()
    Dim xmldoc As New XmlDocument
    Dim noderoot As New TreeNode
    Dim nodetam As XmlNode
    Dim nodePropertiesTam As XmlNode

    'Hàm xử lý đường chỉ file xml
    Function PathFile()
        Dim file_name As String
        file_name = Application.StartupPath
        If file_name.EndsWith("\bin\Debug") Then
            file_name = file_name.Substring(0, file_name.LastIndexOf("\bin\Debug"))
        End If
        file_name &= "\Xml\XmlConfigSubjects.xml"
        Return file_name
    End Function

    'Hàm đọc dữ liệu của node vào treeview
    Private Sub LoadNodeToTreeView(ByVal node As XmlElement, ByVal tv As TreeView)
        tv.Nodes.Clear()
        Dim root As New TreeNode
        'gán node root
        root.Name = node.GetAttribute("type")
        root.Text = node.GetAttribute("type")
        tv.Nodes.Add(root)

        'GÁN NODE CHILD
        For Each n As XmlElement In node
            Dim child As New TreeNode
            child.Name = n.Name
            child.Text = n.Name
            'thêm vào node cha
            root.Nodes.Add(child)
        Next

        'làm mới treeview
        tv.ExpandAll()
    End Sub


    Private Sub btnCreateSubject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateSubject.Click
        If txtSubjectName.Text.Equals("") Then
            MessageBox.Show("Please enter subject")
        Else
            xmldoc.Load(PathFile())

            'nút gốc là Subject
            Dim root As XmlElement = xmldoc.CreateElement("Subject")
            'thuộc tính là type = subjectname
            Dim id As XmlAttribute = xmldoc.CreateAttribute("type")
            'gán giá trị cho thuộc tính
            id.Value = txtSubjectName.Text
            'gán thuộc tính vào nút menuitem
            root.Attributes.Append(id)

            'thêm vào file xml
            xmldoc.DocumentElement.AppendChild(root)

            'lưu lại file xml
            xmldoc.Save(PathFile())
            'thông tin node cha
            noderoot.Name = Convert.ToString(txtSubjectName.Text)
            noderoot.Text = Convert.ToString(txtSubjectName.Text)
            'thêm node cha vào
            trvProperties.Nodes.Add(noderoot)

            'txtSubjectName.ReadOnly = True

            LoadDataXML(PathFile(), dgvListSubject)
        End If
    End Sub

    Private Sub btnCreateProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateProperties.Click
        If txtProperties.Text.Equals("") Then
            MessageBox.Show("Please enter properties")
        Else
            'đọc file xml   
            xmldoc.Load(PathFile())

            'chọn nút tương ứng với id = subjectname
            Dim nodeSub As XmlNode = xmldoc.SelectSingleNode("RootSubject/Subject[@type = '" & Convert.ToString(txtSubjectName.Text) & "']")

            'nút gốc là menuitem
            Dim root As XmlElement = xmldoc.CreateElement(Convert.ToString(txtProperties.Text))

            'gán thẻ root vào node
            nodeSub.AppendChild(root)

            'thêm vào file xml
            xmldoc.DocumentElement.AppendChild(nodeSub)

            'lưu lại file xml
            xmldoc.Save(PathFile())

            'tạo node con
            Dim node As New TreeNode
            node.Name = Convert.ToString(txtProperties.Text)
            node.Text = Convert.ToString(txtProperties.Text)
            'thêm vào node cha
            noderoot.Nodes.Add(node)
            'làm mới treeview
            trvProperties.ExpandAll()

            txtProperties.Text = ""
            txtProperties.Focus()
        End If

    End Sub

    Private Sub LoadDataXML(ByVal path As String, ByVal dgv As DataGridView)

        ' Create a new DataTable.
        Dim datatable As DataTable = New DataTable("SubjectsTable")
        Dim row As DataRow

        datatable.Columns.Add("SubjectsName", Type.GetType("System.String"))
        datatable.Columns.Add("Count", Type.GetType("System.Int32"))

        'đọc dữ liệu trong xml
        Dim xmlDatadoc As New XmlDataDocument
        xmlDatadoc.DataSet.ReadXml(path)
        Dim nodeSub As XmlNode = xmlDatadoc.SelectSingleNode("RootSubject/Subject")
        'đếm số nút có trong node root
        Dim nodeList As XmlNodeList = xmlDatadoc.GetElementsByTagName("Subject")

        For Each node As XmlElement In nodeList
            row = datatable.NewRow()
            row("SubjectsName") = node.GetAttribute("type")
            row("Count") = CountNode(path, node.GetAttribute("type"))

            datatable.Rows.Add(row)
        Next
        dgv.DataSource = datatable

    End Sub

    Function CountNode(ByVal path As String, ByVal nodename As String)
        Dim count As Integer = 0
        'read file xml
        Dim xmldoc As New XmlDocument
        xmldoc.Load(path)
        'choose node
        Dim node As XmlNode = xmldoc.SelectSingleNode("RootSubject/Subject[@type = '" & Convert.ToString(nodename) & "']")
        'counting
        count = node.ChildNodes.Count
        Return count
    End Function


    Private Sub frmSubjects_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadButton(1)
        LoadDataXML(PathFile(), dgvListSubject)
    End Sub

    Private Sub dgvListSubject_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvListSubject.CellClick
        If dgvListSubject.Item(e.ColumnIndex, e.RowIndex).Value = "Update" Then

            LoadButton(2)
            txtSubjectName.Text = dgvListSubject.CurrentRow.Cells("SubjectName").Value
            Dim doc As New XmlDocument
            doc.Load(PathFile())

            Dim node As XmlNode = doc.SelectSingleNode("RootSubject/Subject[@type = '" & Convert.ToString(txtSubjectName.Text) & "']")
            nodetam = node
            LoadNodeToTreeView(node, trvProperties)

        ElseIf dgvListSubject.Item(e.ColumnIndex, e.RowIndex).Value = "Delete" Then

            LoadButton(2)
            Dim response As MsgBoxResult = MsgBox("Bạn có muốn xóa không ?", MsgBoxStyle.OkCancel)
            If response = MsgBoxResult.Ok Then   ' User chose Yes.
                Dim doc As New XmlDocument
                doc.Load(PathFile())

                Dim node As XmlNode = doc.SelectSingleNode("RootSubject/Subject[@type = '" & Convert.ToString(dgvListSubject.CurrentRow.Cells("SubjectName").Value) & "']")
                node.ParentNode.RemoveChild(node)
                doc.Save(PathFile())
                'DeleteNode(node, PathFile())

                MessageBox.Show("Xóa thành công.")
                LoadDataXML(PathFile(), dgvListSubject)
                trvProperties.Nodes.Clear()
            End If
        End If
    End Sub

    Private Sub LoadButton(ByVal x As Int16)
        txtSubjectName.Text = ""
        txtProperties.Text = ""
        If x = 1 Then
            txtSubjectName.ReadOnly = False
            btnCreateProperties.Enabled = True
            btnCreateSubject.Enabled = True
            btnUpdateProperties.Enabled = False
            Update.Enabled = False
            btnDeleteProperties.Enabled = False
            Button1.Visible = False
        Else
            txtSubjectName.ReadOnly = False
            btnCreateProperties.Enabled = False
            btnCreateSubject.Enabled = False
            btnUpdateProperties.Enabled = True
            Update.Enabled = True
            btnDeleteProperties.Enabled = True
            Button1.Visible = True
        End If
    End Sub

    Private Function EditSubjectName(ByVal path As String, ByVal node As XmlElement, ByVal subjectname As String) As XmlElement
        Dim doc As New XmlDocument
        doc.Load(path)
        Dim nodeCurrent As XmlElement = doc.SelectSingleNode("RootSubject/Subject[@type = '" & node.GetAttribute("type") & "']")
        nodeCurrent.SetAttribute("type", subjectname)
        doc.Save(path)
        EditSubjectName = nodeCurrent
    End Function

    Private Function EditPropertiesName(ByVal path As String, ByVal node As XmlElement, ByVal newPropertiesName As String, ByVal subject As String) As XmlElement
        Dim doc As New XmlDocument
        doc.Load(path)
        Dim newChild As XmlElement = doc.CreateElement(newPropertiesName)
        Dim nodeCurrent As XmlElement = doc.SelectSingleNode("RootSubject/Subject[@type = '" & subject & "']")
        For Each childNode As XmlElement In nodeCurrent
            If childNode.Name = node.Name Then
                nodeCurrent.ReplaceChild(newChild, childNode)
            End If
        Next
        doc.Save(path)
        MessageBox.Show("Sửa đổi thuộc tính thành công")
        EditPropertiesName = nodeCurrent
    End Function

    Private Sub Update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Update.Click
        If txtSubjectName.Text.Equals("") Then
            MessageBox.Show("Please enter subject")
        Else
            Dim node As XmlElement = EditSubjectName(PathFile(), nodetam, txtSubjectName.Text)

            LoadDataXML(PathFile(), dgvListSubject)
            LoadNodeToTreeView(node, trvProperties)
        End If
    End Sub

    Private Sub trvProperties_NodeMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles trvProperties.NodeMouseClick
        If e.Node.Parent Is Nothing Then
            txtSubjectName.Text = e.Node.Text
        Else
            txtProperties.Text = e.Node.Text
            Dim doc As New XmlDocument
            doc.Load(PathFile())

            Dim node As XmlNode = doc.SelectSingleNode("RootSubject/Subject[@type = '" & Convert.ToString(txtSubjectName.Text) & "']")
            For Each ChildNode As XmlElement In node
                If ChildNode.Name = e.Node.Text Then
                    nodePropertiesTam = ChildNode
                End If
            Next
        End If

    End Sub

    Private Sub btnDeleteProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteProperties.Click
        Dim doc As New XmlDocument
        doc.Load(PathFile())

        Dim node As XmlNode = doc.SelectSingleNode("RootSubject/Subject[@type = '" & Convert.ToString(txtSubjectName.Text) & "']")
        For Each ChidlNode As XmlNode In node
            If ChidlNode.Name = txtProperties.Text Then
                node.RemoveChild(ChidlNode)
            End If
        Next
        doc.Save(PathFile())
        'DeleteNode(node, PathFile())
        txtProperties.Text = ""
        MessageBox.Show("Xóa thành công thuộc tính thành công.")
        LoadDataXML(PathFile(), dgvListSubject)
        LoadNodeToTreeView(node, trvProperties)
    End Sub

    Private Sub btnUpdateProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateProperties.Click
        If txtProperties.Text.Equals("") Then
            MessageBox.Show("Please enter subject")
        Else
            Dim node As XmlElement = EditPropertiesName(PathFile(), nodePropertiesTam, txtProperties.Text, txtSubjectName.Text)

            LoadDataXML(PathFile(), dgvListSubject)
            LoadNodeToTreeView(node, trvProperties)
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        LoadButton(1)
    End Sub
End Class